<template>
  <div class="top">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/Classification">课程管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/Video">视频管理</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="middel">
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
      <el-form-item label="视频名称">
        <el-input v-model="queryInfo.videoName" placeholder="请输入视频名称" clearable />
      </el-form-item>
      <el-form-item label="所属课程">
        <el-select
          v-model="queryInfo.courseId"
          placeholder="请选择所属课程"
          clearable
          filterable
          style="width: 220px"
        >
          <el-option
            v-for="item in courseOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="openDialog('add')">新增视频</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="batchDelete" :disabled="multipleSelection.length === 0">
          批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="content">
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      row-key="id"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :loading="loading"
      border
      stripe
      class="category-table"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="视频ID" width="100" align="center" />
      <el-table-column
        prop="name"
        label="视频名称"
        min-width="180"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column label="视频" width="160">
        <template #default="scope">
          <div @click="handlePreview(scope.row.url)" style="cursor: pointer">
            <video
                :src="`http://localhost:8080${scope.row.url}`"
              style="width: 120px; height: 80px; border-radius: 6px; background: #000"
              controls
              muted
              preload="metadata"
              @click.stop
            />
            <div style="font-size: 12px; color: #888; text-align: center">点击预览</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="timeStr" label="视频时长" width="120" align="center" />
      <el-table-column
        prop="courseName"
        label="所属课程"
        min-width="150"
        align="center"
        show-overflow-tooltip
      />

      <el-table-column label="操作" width="240" align="center">
        <template #default="scope">
          <div style="display: flex; justify-content: center; gap: 16px">
            <el-button size="small" type="primary" @click="openDialog('edit', scope.row)"
              >编辑</el-button
            >
            <el-button size="small" type="danger" @click="deleteVideo(scope.row.id)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px"
    />
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
    <el-form :model="form" label-width="110px" class="dialog-form">
      <el-form-item label="视频名称" required>
        <el-input v-model="form.videoName" autocomplete="off" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="视频文件">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/upload"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleVideoUploadSuccess"
          :on-error="handleUploadError"
          :data="uploadData"
          accept="video/*"
        >
          <el-icon v-if="!form.videoView"><Plus /></el-icon>
          <span v-else>更换视频</span>
        </el-upload>
        <div v-if="form.videoView" style="margin-top: 10px">
          <video :src="`http://localhost:8080${form.videoView}`"
            controls
            style="max-width: 100%; max-height: 200px; border-radius: 6px; background: #000"
          />
        </div>
      </el-form-item>

      <el-form-item label="所属课程" required>
        <el-select v-model="form.courseId" placeholder="请选择课程" filterable style="width: 100%">
          <el-option
            v-for="item in courseOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="videoPreviewVisible" title="视频预览" width="600">
    <video
      v-if="previewUrl"
      :src="`http://localhost:8080${previewUrl}`"
      controls
      autoplay
      style="width: 100%; max-height: 400px; background: #000; border-radius: 8px"
    />
  </el-dialog>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus'

// 查询参数
const queryInfo = reactive({
  id: '',
  videoName: '',
  courseName: '',
  pageSize: 10,
  pageNum: 1,
  courseId: '',
})

// 表格数据和分页
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 选择相关
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<any[]>([])

const axios = getCurrentInstance().appContext.config.globalProperties.axios

// 弹窗表单
const dialogVisible = ref(false)
const dialogTitle = ref('新增视频')
let form = reactive({
  id: '',
  videoName: '',
  videoView: '',
  courseName: '',
  courseId: '',
})
let dialogMode = 'add'

// 课程选项
const courseOptions = ref([])
const fetchCourseOptions = () => {
  axios.get('course').then((resp) => {
    if (resp.code === 200) {
      courseOptions.value = resp.data.map((item) => ({
        id: item.id,
        name: item.name,
      }))
    }
  })
}

// 监听搜索下拉框变化，自动同步课程名
watch(
  () => queryInfo.courseId,
  (newVal) => {
    const selected = courseOptions.value.find((item) => item.id === newVal)
    queryInfo.courseName = selected ? selected.name : ''
  },
)

// 监听弹窗表单的课程下拉框变化，自动同步课程名
watch(
  () => form.courseId,
  (newVal) => {
    const selected = courseOptions.value.find((item) => item.id === newVal)
    form.courseName = selected ? selected.name : ''
  },
)

// 查询列表
const queryDataList = () => {
  loading.value = true
  axios
    .post(
      'courseVideo/page',
      {
        name: queryInfo.videoName || null,
        courseName: queryInfo.courseName || null,
      },
      {
        params: {
          pageNum: queryInfo.pageNum,
          pageSize: queryInfo.pageSize,
        },
      },
    )
    .then((response) => {
      console.log(response)
      if (response && response.code === 200) {
        tableData.value = response.data.list || []
        total.value = response.data.total || 0
        // console.log('tableData.value:',tableData.value);
      } else {
        ElMessage.error(response.message || '查询失败')
      }
    })
    .catch(() => {
      ElMessage.error('网络请求错误，请检查网络连接或服务器状态')
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  queryDataList()
  fetchCourseOptions()
})

// 搜索
const search = () => {
  queryInfo.pageNum = 1
  queryDataList()
}

// 分页
const handleSizeChange = (size: number) => {
  queryInfo.pageSize = size
  queryDataList()
}
const handleCurrentChange = (num: number) => {
  queryInfo.pageNum = num
  queryDataList()
}

// 选择
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

// 打开弹窗
function openDialog(mode: 'add' | 'edit', row?: any) {
  dialogMode = mode
  fetchCourseOptions()
  if (mode == 'add') {
    dialogTitle.value = '新增视频'
    form.id = ''
    form.videoName = ''
    form.videoView = ''
    form.courseId = ''
  } else if (mode == 'edit' && row) {
    dialogTitle.value = '编辑视频'
    axios.get(`courseVideo/${row.id}`).then((resp: any) => {
      if (resp.code === 200) {
        form.id = resp.data.id
        form.videoName = resp.data.name
        form.videoView = resp.data.url
        form.courseId = resp.data.courseId
        // 主动同步一次 courseName，确保编辑时有值
        const syncCourseName = () => {
          const selected = courseOptions.value.find((item) => item.id === resp.data.courseId)
          form.courseName = selected ? selected.name : ''
        }
        if (courseOptions.value.length > 0) {
          syncCourseName()
        } else {
          // 如果还没加载完，等加载完再同步
          const stop = watch(courseOptions, (val) => {
            if (val.length > 0) {
              syncCourseName()
              stop()
            }
          })
        }
      } else {
        ElMessage.error('请求失败')
      }
    })
  }
  dialogVisible.value = true
}

// 上传相关
const uploadData = reactive({}) // 可根据需要传递额外参数

function beforeUpload(file) {
  // 可在此校验文件类型/大小
  return true
}

function handleUploadError() {
  ElMessage.error('图片上传失败')
}

function handleVideoUploadSuccess(response) {
  // 兼容后端返回 { url }、{ data }、{ videoView }
  const url = response.url || response.data || response.videoView
  if (url) {
    form.videoView = url
    ElMessage.success('视频上传成功')
  } else {
    ElMessage.error('视频上传失败')
  }
}

// 新增/编辑提交
function submitForm() {
  if (!form.videoName.trim()) {
    ElMessage.warning('请输入视频名称')
    return
  }
  if (!form.courseName.trim()) {
    ElMessage.warning('请输入所属课程')
    return
  }

  if (dialogMode === 'add') {
    console.log(form)
    axios
      .post('courseVideo', {
        name: form.videoName,
        url: form.videoView,
        courseName: form.courseName,
        courseId: form.courseId,
      })
      .then((resp: any) => {
        if (resp.code === 200) {
          ElMessage.success('新增成功')
          dialogVisible.value = false
          queryDataList()
        } else {
          ElMessage.error(resp.message || '新增失败')
        }
      })
  } else if (dialogMode === 'edit') {
    axios
      .put('courseVideo', {
        id: form.id,
        name: form.videoName,
        url: form.videoView,

        courseName: form.courseName,
        courseId: form.courseId,
      })
      .then((resp: any) => {
        console.log('1111' + resp)
        if (resp.code === 200) {
          ElMessage.success('编辑成功')
          dialogVisible.value = false
          queryDataList()
        } else {
          ElMessage.error(resp.message || '编辑失败')
        }
      })
  }
}

// 删除
function deleteVideo(id: number) {
  ElMessageBox.confirm('确定要删除该视频吗？', '提示', {
    type: 'warning',
  }).then(() => {
    axios.delete(`courseVideo/${id}`).then((resp: any) => {
      if (resp.code === 200) {
        ElMessage.success('删除成功')
        queryDataList()
      } else {
        ElMessage.error(resp.message || '删除失败')
      }
    })
  })
}

// 批量删除
function batchDelete() {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的视频')
    return
  }
  ElMessageBox.confirm('确定要批量删除选中的视频吗？', '提示', {
    type: 'warning',
  }).then(() => {
    const ids = multipleSelection.value.map((item: any) => item.id).join(',')
    axios
      .delete('courseVideo/batch', {
        params: { ids },
      })
      .then((resp: any) => {
        if (resp.code === 200) {
          ElMessage.success('批量删除成功')
          queryDataList()
        } else {
          ElMessage.error(resp.message || '批量删除失败')
        }
      })
  })
}
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'

const dialogImageUrl = ref('')
const disabled = ref(false)

const handleRemove = (file: UploadFile) => {
  console.log(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
  console.log(file)
}

const videoPreviewVisible = ref(false)
const previewUrl = ref('')
function handlePreview(url) {
  previewUrl.value = url
  videoPreviewVisible.value = true
}
</script>

<style scoped>
.top {
  background-color: #f8f9fa;
  padding: 12px 20px;
  margin-bottom: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.el-breadcrumb {
  max-width: 1200px;
  margin: 0 auto;
}
.middel {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.demo-form-inline {
  display: flex;
  align-items: center;
  gap: 15px;
}
.demo-form-inline .el-form-item {
  margin-right: 20px;
}
.demo-form-inline .el-input,
.demo-form-inline .el-select {
  width: 220px;
}
.el-button {
  min-width: 100px;
}
.el-button + .el-button {
  margin-left: 10px;
}
.content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.category-table {
  background: #fff;
  border-radius: 8px;
}
.el-table {
  margin-bottom: 20px;
}
.el-table__header-wrapper {
  border-radius: 6px 6px 0 0;
}
.el-table__body-wrapper {
  border-radius: 0 0 6px 6px;
}
.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px !important;
}
.dialog-form {
  padding-top: 10px;
}
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
